package com.erji.admin.controller.system;

import com.erji.common.constant.StringPool;
import com.erji.common.core.domain.R;
import com.erji.common.cos.FileManager;
import com.erji.common.cos.constant.FileConstants;
import com.erji.common.cos.domain.FileObject;
import com.erji.common.utils.uuid.UUID;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Api(tags = "文件模块", value = "文件模块")
@RestController
@RequestMapping("/web/v1/file")
public class UploadController {

    private final static Logger logger = LoggerFactory.getLogger(UploadController.class);

    @Autowired
    private FileManager fileManager;


    @ApiOperation(value = "文件上传", notes = "sub_path 默认传template")
    @PostMapping("/upload//{subPath}")
    public R<FileObject> upload(@PathVariable("subPath") String subPath, @RequestParam("file") MultipartFile file) {
        try {
            return R.ok(uploadMultipartFile(file, subPath));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return R.ok();
    }

    @ApiOperation(value = "上传临时文件", notes = "上传临时文件")
    @PostMapping(value = "/upload/temp")
    public R<FileObject> uploadTemplateFile(@RequestParam("file") MultipartFile file) {
        try {
            return R.ok(uploadMultipartFile(file, FileConstants.DEFAULT_FOLDER));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return R.ok();
    }

    private FileObject uploadMultipartFile(MultipartFile multipartFile, String folder) {
        String multiFileName = multipartFile.getOriginalFilename();
        String uuid = String.valueOf(UUID.randomUUID()).replaceAll(StringPool.DASH, StringPool.BLANK);
        String ext = multiFileName.substring(multiFileName.lastIndexOf(StringPool.PERIOD));
        try {
            FileObject fileObject = fileManager.upload(multiFileName, folder + StringPool.SLASH + uuid + ext, multipartFile.getInputStream(), -1);
            return fileObject;
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
        return new FileObject();
    }

}


